package com.hnkywl.sts.util;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Fei on 2015/12/9.
 */
public class Tools {
    /**
     * 获取实体字段
     *
     * @param clazz
     * @return
     */
    public static String[] getFields(Class clazz) {

        Field[] fs = clazz.getDeclaredFields();
        String fields[] = new String[fs.length];
        for (int i = 0; i < fs.length; i++) {
            fields[i] = fs[i].getName();
        }
        return fields;
    }

    /**
     * 实体转换为Map
     *
     * @param obj
     * @return
     */
    public static Map ConvertObjToMap(Object obj) {
        Map reMap = new HashMap();
        if (obj == null)
            return null;
        Field[] fields = obj.getClass().getDeclaredFields();
        try {
            for (int i = 0; i < fields.length; i++) {
                try {
                    Field f = obj.getClass().getDeclaredField(fields[i].getName());
                    f.setAccessible(true);
                    Object o = f.get(obj);
                    reMap.put(fields[i].getName(), ObjToString(o));
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return reMap;
    }


//    /**
//     * 将字符串格式实体转换为实体类
//     * @param strEntity
//     * @return
//     */
//    public static AccountEntity StringToEntity(String strEntity){
//        AccountEntity accountEntity = null;
//        try {
//            Class clasz = Class.forName(strEntity);
//            Object enity = clasz.newInstance();
//            accountEntity = (AccountEntity) enity;
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        return accountEntity;
//    }

    /**
     * 数据库字段转驼峰
     * <p>例：AA_BB_CC --> aaBbCc
     *
     * @param srcName
     * @return
     */
    public static String getEntityName(String srcName) {
        String name = "";
        for (int i = 0; i < srcName.length(); i++) {
            if (0 == i) {
                name += srcName.substring(i, i + 1).toLowerCase();
            } else if ('_' == srcName.charAt(i)) {
                continue;
            } else if ('_' == srcName.charAt(i - 1)) {
                name += srcName.substring(i, i + 1).toUpperCase();
            } else {
                name += srcName.substring(i, i + 1).toLowerCase();
            }
        }
        return name;
    }

    /**
     * 根据传入类型精度信息转换相应值
     *
     * @param fieldType
     * @param fieldPrecision
     * @param fieldLen
     * @param value
     * @return
     */
    public static Object getFieldValue(String fieldType, int fieldPrecision, int fieldLen, Object value) {
        if (fieldType.equals("C")) {
            String val = Tools.NullToString(value);
            return val;
        } else if (fieldType.equalsIgnoreCase("N")) {
            if (fieldPrecision > 0) {
                Double val = Tools.NullToDouble(value);
                return val.doubleValue();
            } else if (fieldPrecision == 0) {
                if (fieldLen <= 5) {
                    Integer val = Tools.NullToInteger(value);
                    return val.intValue();
                } else if (fieldLen > 5) {
                    Long val = Tools.NullToLong(value);
                    return val.longValue();
                }
            }
        }
        return "";
    }


    /**
     * obj转换为字符串
     *
     * @param obj
     * @return
     */
    public static String ObjToString(Object obj) {
        if (obj == null) {
            return "";
        }
        if ((obj instanceof Date)) {
            //return DateUtils.toDateStr((Date)obj);
            return new SimpleDateFormat("yyyy-MM-dd").format((Date) obj);
        }

        return obj.toString();
    }


    /**
     * 数字求和
     *
     * @param v1
     * @param v2
     * @return
     */
    public static Double add(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1 == null ? "0" : v1.toString());
        BigDecimal b2 = new BigDecimal(v2 == null ? "0" : v2.toString());
        return b1.add(b2).doubleValue();
    }

    /**
     * 数字求差
     *
     * @param v1 减数
     * @param v2 被减数
     * @return
     */
    public static Double sub(Double v1, Double v2) {
        BigDecimal b1 = new BigDecimal(v1 == null ? "0" : v1.toString());
        BigDecimal b2 = new BigDecimal(v2 == null ? "0" : v2.toString());
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 数字求乘
     *
     * @param v1
     * @param v2
     * @param num 保留小数位数
     * @return
     */
    public static Double mul(Double v1, Double v2, Object num) {
        try {
            BigDecimal b1 = new BigDecimal(v1 == null ? "0" : v1.toString());
            BigDecimal b2 = new BigDecimal(v2 == null ? "0" : v2.toString());
            Double dd = new Double(0);
            if (num == null) {
                dd = (b1.multiply(b2)).doubleValue();
            } else {
                dd = (b1.multiply(b2)).setScale(Integer.parseInt(num.toString()), BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            return dd;
        } catch (Exception e) {
            throw new RuntimeException(e.getStackTrace().toString());
        }

    }

    /**
     * 数字相除
     *
     * @param v1  除数
     * @param v2  被除数
     * @param num 保留小数位数
     * @return
     */
    public static Double div(Double v1, Double v2, Object num) {
        try {
            BigDecimal b1 = new BigDecimal(v1 == null ? "0" : v1.toString());
            BigDecimal b2 = new BigDecimal(v2 == null ? "0" : v2.toString());
            if (b2.doubleValue() == 0) {
                b2 = new BigDecimal(1);
            }
            Double dd = new Double(0);
            // 结果保留两位小数，四舍五入
            if (num == null) {
                throw new RuntimeException("小数保留位数为空！");
            } else {
                dd = b1.divide(b2, Integer.parseInt(num.toString()), BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            return dd;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * NULL转换为String
     * <p> null-->""
     */
    public static String NullToString(Object value) {
        return value == null ? "" : value.toString();
    }

    /**
     * NULL转换为BigDecimal
     * <p>null-->0
     *
     * @param value
     * @return
     */
    public static BigDecimal NullToBigDecimal(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }

    /**
     * NULL转换为Integer
     * <p>null-->0
     *
     * @param value
     * @return
     */
    public static Integer NullToInteger(Object value) {
        if (value == null || value.equals(""))
            return 0;
        else
            return Integer.parseInt(value.toString());
    }

    /**
     * NULL转换为Long
     * <p>null-->0
     *
     * @param value
     * @return
     */
    public static Long NullToLong(Object value) {
        if (value == null || value.equals(""))
            return new Long(0);
        else
            return Long.parseLong(value.toString());
    }

    /**
     * Null转换为Double
     * <p>null-->new Double(0)
     *
     * @param value
     * @return
     */
    public static Double NullToDouble(Object value) {
        if (value == null || value.equals(""))
            return new Double(0);
        else
            return Double.parseDouble(value.toString());
    }

    /**
     * 将json格式的字符串，按{}分开，存入list
     *
     * @param jsonString [{"a":"xx","b":"yy", ...},{"a":"zz","b":"gg", ...}, ...]
     * @return
     */
    public List jsonStrToList(String jsonString) {
        JsonElement je = null;
        List list = new ArrayList();
        JsonParser jsonParser = new JsonParser();
        je = jsonParser.parse(jsonString);
        JsonArray jsonArray = null;
        if (je.isJsonArray()) {
            jsonArray = je.getAsJsonArray();
            Iterator it = jsonArray.iterator();
            while (it.hasNext()) {
                je = (JsonElement) it.next();
                list.add(je);
            }
        }
        return list;
    }
}
